<template>
    <div class="list-page">

        <tool-bar nav="">
            <el-button @click="bind_target_click">对比环境</el-button>
            <div v-if="target.k8sApiHost" style="margin:auto 8px;">
                <el-tag>{{ target.k8sApiHost }}</el-tag>
                <el-tag>{{ target.k8sNamespace }}</el-tag>
                <el-tag>{{ target.appGroup }}</el-tag>
                <el-tag>{{ target.envProfile }}</el-tag>
            </div>
            <el-button @click="export_click">导出Excel</el-button>
        </tool-bar>

        <el-dialog title="目标k8s" v-model="target_dlg">

            <kv><template #k>
                <div class="k">
                    目标环境
                    <remark>
                        <div> 目标环境的 默认环境和目标环境必须是一致的。</div>
                        <div> 如 目标环境是 192.168.1.1 其默认环境不能指向 192.168.1.2</div>
                    </remark>
                </div></template>
                <app-env v-model="target_edit.referK8sEnv" @change="target_change"></app-env>
            </kv>
            <kv label="名称空间">
                <el-input v-model="target_edit.k8sNamespace"
                ></el-input>
            </kv>
            <kv label="appGroup">
                <el-input v-model="target_edit.appGroup"
                ></el-input>
            </kv>
            <kv label="envProfile">
                <el-input v-model="target_edit.envProfile"
                ></el-input>
            </kv>

            <kv label="启用istio">
                <el-switch
                    v-model="target_edit.istio">
                </el-switch>
            </kv>

            <el-button @click="fetch_click()">确定</el-button>
        </el-dialog>
        <my-list
            ref="list"
            @param="preload"
            @loaded="procData"
            :page-size="10"
            :store="true"
            :query.sync="query"
            :row-class-name="rowClass"
            row-key="id"
            @query="list_query"
        >


            <el-table-column label="名称" align="left" width="240">
                <template v-slot="scope">
                    <div class="link cell-name" @click="edit_click(scope.row)">{{ scope.row.name }}</div>
                </template>
            </el-table-column>
            <!--      <el-table-column align="left" label="镜像名" prop="imageName" min-width="240"></el-table-column>-->
            <el-table-column align="left" label="当前环境版本" min-width="240">
                <template v-slot="scope">
                    <el-tag v-if="!scope.row?.vt">{{ scope.row.imageVersion }}</el-tag>
                    <el-tag effect="dark"
                            v-else-if="scope.row?.vt == 'dev'">
                        {{ scope.row.imageVersion }}
                    </el-tag>
                    <el-tag type="warning" v-else>{{ scope.row.imageVersion }}</el-tag>

                    <el-tag v-if="scope.row?.readyReplicas == scope.row.replicas">{{
                            scope.row.readyReplicas
                        }}/{{ scope.row.replicas }}
                    </el-tag>
                    <el-tag type="danger" v-else>{{ scope.row.readyReplicas }}/{{ scope.row.replicas }}</el-tag>

                    <el-tag type="danger" title="非最新Rs版本" v-if="!scope.row?.isLatestRsVersion">!</el-tag>

                </template>
            </el-table-column>
            <el-table-column align="left" label="对比环境版本" min-width="240">
                <template v-slot="scope">
                    <div @click="refresh_test(scope.row)" class="btn" title="点击刷新数据">
                        <el-tag v-if="!scope.row?.vt">
                            {{ scope.row.test_imageVersion }}
                        </el-tag>
                        <el-tag effect="dark"
                                v-else-if="scope.row?.vt == 'test'">
                            {{ scope.row.test_imageVersion }}
                        </el-tag>
                        <el-tag type="warning" v-else-if="scope.row?.test_imageVersion">
                            {{ scope.row.test_imageVersion }}
                        </el-tag>
                    </div>

                    <el-tag
                        v-if="scope.row?.test_replicas && scope.row?.test_readyReplicas == scope.row?.test_replicas">{{
                            scope.row.test_readyReplicas
                        }}/{{ scope.row.test_replicas }}
                    </el-tag>

                    <el-tag type="danger" v-else-if="scope.row?.test_replicas">{{
                            scope.row.test_readyReplicas
                        }}/{{ scope.row.test_replicas }}
                    </el-tag>

                    <el-tag type="danger" title="非最新Rs版本"
                            v-if="!scope.row?.test_isLatestRsVersion && scope.row?.test_imageVersion">
                        !
                    </el-tag>

                </template>
            </el-table-column>
            <el-table-column label="差距" align="left" class-name="cell-flex" width="80">
                <template v-slot="scope">
                    <el-tag :type=" scope.row.diff_ver.endsWith('后')? 'danger':'primary' ">{{ scope.row.diff_ver }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="160">
                <template v-slot="scope">
                    <el-button v-if="target.k8sApiHost" @click="sync_dev(scope.row)" :disabled="!scope.row.vt">
                        同步到目标环境
                    </el-button>
                </template>
            </el-table-column>
            <template #query="scope">
                <kv><template #k>
                    <div class="k">
                        源K8s
                        <remark>
                            <div> 目标环境的 默认环境和目标环境必须是一致的。</div>
                            <div> 如 目标环境是 192.168.1.1 其默认环境不能指向 192.168.1.2</div>
                        </remark>
                    </div></template>
                    <app-env v-model="scope.query.targetEnv"
                             @change="env_change"></app-env>
                </kv>
                <kv label="语言">
                    <selector v-model="scope.query.language" enum="JenkinsLanguageEnum" chk="*"></selector>
                </kv>
                <kv label="产品线">
                    <product-line :key="scope.query.language" :language="scope.query.language"
                                  v-model="scope.query.productLineCode" style="flex:1;" chk="*"
                                  @change="productLine_change"></product-line>

                    <el-tag>{{ scope.query.productLineCode }}</el-tag>
                </kv>


                <kv label="名称">
                    <el-input v-model="scope.query.name"></el-input>
                </kv>

                <kv label="状态">
                    <selector v-model="scope.query.isReady" :data="{true:'就绪',false:'异常','':'全部'}"></selector>
                </kv>
            </template>
            <template #button>
                <el-button @click="loadData">刷新</el-button>
            </template>
        </my-list>
    </div>
</template>
<style scoped lang="scss">
.btn {
    display: inline-block;
    cursor: pointer;
    margin-right: 8px;
}

.btn:hover span {
    opacity: 0.8;
    border-bottom: solid 1px gray;
}

::v-deep(tr.row-java) .cell-name {
    color: #1e4a90;
}

::v-deep(tr.row-vue) .cell-name {
    color: #694002;
}

::v-deep(tr.row-node) .cell-name {
    color: #286f04;
}
</style>
<script setup>
/**
 * Created by CodeGenerator at 2021-03-14 15:58:11
 */
import productLine from "@/component/product-line.vue";
import appEnv from "@/component/app-env.vue"





//定义 vue2的this,当前组件
const $self = getCurrentInstance();

//定义 $attrs
const $attrs = useAttrs();



//定义data
const $data = reactive({"target_dlg":false,"target":{"istio":false,"referK8sEnv":"","k8sApiHost":"","k8sNamespace":"default","envProfile":"test"},"target_edit":{"istio":false,"referK8sEnv":"","k8sApiHost":"","k8sNamespace":"default","envProfile":"test"},"products":[],"list":[],"query":{"language":"Java","productLineCode":"","targetEnv":""},"sourceK8sApiHost":""});


const $props = defineProps({

});





const list = ref();

//定义事件
const $emit = defineEmits(["update:modelValue","loaded"]);



const env_change = function(v, m) {
    $data.sourceK8sApiHost = m && m.url || "" ;
};
const list_query = function() {
    if (!$data.sourceK8sApiHost) {
        return jv.error("找不到 sourceK8sApiHost");
    }
    list.value.url = $data.sourceK8sApiHost + '/ops/k8s/deployment/list';
};
const rowClass = function(rowOpt) {
    return "row-" + rowOpt.row.name.split('-').getLast()
};
const bind_target_click = function() {
    $data.target_dlg = true;
    $data.target_edit = Object.assign({}, $data.target);
};
const export_click = function() {
    jv.info("未实现")
};
const productLine_change = function(v, m, p) {
    $data.target.k8sNamespace = $data.target.k8sNamespace || v;
    $data.target.appGroup = $data.target.appGroup || v;
};
const refresh_test = function(row) {
    fetch_work([row]);
};
const target_change = function(v, data) {
    $data.target_edit.k8sApiHost = data.url;
};
const sync_done = function(row) {
    sync_done_number++;
    if (sync_done_number >= 3) {
        setTimeout(() => {
            fetch_work([row])
        }, 1000);
        setTimeout(() => {
            fetch_work([row])
        }, 10000);
    }
};
const sync_dev = function(row) {
    sync_done_number = 0;
    var svcName = row.name;
    if (svcName.endsWith("-java")) {
        svcName = svcName.slice(0, -5);
    }
    var localMpUrl = jv.getFullUrl($data.sourceK8sApiHost, "/ops/k8s/configmap/get?") +
        jv.param({namespace: $data.query.productLineCode, name: svcName});
    jv.$http.post(localMpUrl).then(res => {
        var configMap = res.data.data;
        var url = jv.getFullUrl($data.target.k8sApiHost) + '/ops/k8s/configmap/set?' +
            jv.param({namespace: $data.target.k8sNamespace, name: svcName});
        jv.$http.post(url, {content: configMap}).then(res => {
            sync_done(row)
        })
    })
    var localMpUrl = jv.getFullUrl($data.sourceK8sApiHost, "/ops/k8s/service/get-service-yaml?") +
        jv.param({namespace: $data.query.productLineCode, name: row.name})
    jv.$http.post(localMpUrl).then(res => {
        var yaml = res.data.data;
        var url = jv.getFullUrl($data.target.k8sApiHost) + '/ops/k8s/service/apply-service-yaml?' +
            jv.param({namespace: $data.target.k8sNamespace, name: row.name});
        jv.$http.post(url, yaml, {headers: {"Content-Type": "text/plain"}}).then(res => {
            sync_done(row)
        })
    });
    localMpUrl = jv.getFullUrl($data.sourceK8sApiHost, "/ops/k8s/deployment/get-deployment-yaml?") +
        jv.param({namespace: $data.query.productLineCode, name: row.name})
    jv.$http.post(localMpUrl).then(res => {
        var yaml = res.data.data;
        var p = {};
        p.namespace = $data.target.k8sNamespace;
        p.name = row.name;
        p.appGroup = $data.target.appGroup;
        p.envProfile = $data.target.envProfile;
        p.enableIstio = !$data.target.istio;
        var url = $data.target.k8sApiHost + '/ops/k8s/deployment/apply-deployment-yaml?' + jv.param(p);
        jv.$http.post(url, yaml, {headers: {"Content-Type": "text/plain"}}).then(res => {
            sync_done(row);
        })
    });
};
const preload = function(param, callback) {
    if (!list.value.$refs.query.chk()) {
        return callback(false);
    }
//添加查询参数，修改分页参数等。
//param.type = jv.$route.params.type
};
const procData = function(res) {
    res.data.data.forEach(row => {
        row.test_imageVersion = ""
        row.vt = "";
        row.test_readyReplicas = 0
        row.test_replicas = 0
        row.test_isLatestRsVersion = false
        row.diff_ver = ""
        row.id = row.name;
    })
    $data.list = res.data.data
    fetch_work()
};
const fetch_click = function() {
    $data.target = Object.assign({}, $data.target_edit);
    $data.target_dlg = false;
    jv.$saveData("target",$data.target)
    fetch_work();
};
const fetch_work = function(list) {
    if (!$data.target.k8sApiHost) {
        return;
    }
    list = list || $data.list;
    var p = {};
    p.names = list.map(it => it.name);
    p.take = 99;
    p.namespace = $data.target.k8sNamespace;
    p.productLineCode = $data.query.productLineCode;
    p.language = $data.query.language;
    var url = $data.target.k8sApiHost + '/ops/k8s/deployment/list';
    jv.$http.post(url, p).then(res2 => {
        list.forEach(row => {
            var item = res2.data.data.find(it => it.name == row.name)
            if (item == null) {
                row.vt = "dev"
                return;
            }
            row.test_imageVersion = item.imageVersion
            row.test_replicas = item.replicas
            row.test_readyReplicas = item.readyReplicas
            row.test_isLatestRsVersion = item.isLatestRsVersion
            row.vt = "";
            if (!row.test_imageVersion) {
                row.vt = "dev"
            } else if (row.imageVersion > row.test_imageVersion) {
                row.vt = "dev"
            } else if (row.imageVersion < row.test_imageVersion) {
                row.vt = "test"
            }
            if (row.imageVersion && row.test_imageVersion) {
                row.diff_ver = jv.getTimeDiffSummary(Date.from(row.imageVersion) - Date.from(row.test_imageVersion)) || "=="
            }
        })
    })
};
const loadData = function(pageNumber) {
    list.value.loadData(pageNumber);
};
const edit_click = function(row) {
//记录上次点击行
    var rowId = row.id;
    list.value.setLastRow(row);
};
const delete_click = function(row) {
    var rowId = row.id;
    var rowName = row.name;
    jv.confirm('确认删除 ' + rowName + ' 吗？').then(res => {
        jv.$http.post("/admin/admin-menu/delete/" + rowId).then(res => {
//[axios拦截器中已处理了异常]。
            loadData();
        })
    });
};
const set_click = function(row) {
//设置事件
    var rowId = row.id;
};

onMounted( function() {
    jv.$loadData("target", v=> $data.target = v )
    jv.$loadData("query", v=> $data.query = v )
} )



</script>